//
//  ColloquyStatz.m
//  Statz
//
//  Created by dmaclach on 6/17/07.
//
// Copyright 2007 Google Inc.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.
//

#import "ColloquyStatz.h"
#import "AEVTBuilder.h"
#import "StatusUpdate.h"
#import <Carbon/Carbon.h>

@implementation ColloquyStatz

- (NSString*)appBundleID {
  return @"info.colloquy";
}

- (NSString*)uuid {
  return @"2F5C305F-0149-4F23-B305-11654806A455";
}

- (void)dealloc {
  [oldValue_ release];
  [super dealloc];
}

- (StatzUpdateValue)updateStatz:(StatusUpdate*)sender {
  NSString *newValue = [sender status];
  if ([sender state] != kStatzStateAway) {
    newValue = @"";
  }
  if ([newValue isEqualToString:oldValue_]) return kStatzUpdateNotChanged;
  
  OSType type = kAEAll;
  NSData *typeAll = [NSData dataWithBytes:&type length:sizeof(type)];
  NSAppleEventDescriptor *getConnectionsEvent = [AEVT class:kAECoreSuite 
                                                         id:kAEGetData
                                             targetBundleID:[self appBundleID],
    [KEY:keyDirectObject],
    [RECORD:cObjectSpecifier,
      [KEY:keyAEKeyForm], [ENUM:formAbsolutePosition],
      [KEY:keyAEDesiredClass], [TYPE : 'conM'],
      [KEY:keyAEKeyData], [DATA:typeAbsoluteOrdinal, typeAll],
      [KEY:keyAEContainer], [DESC null],
      ENDRECORD],
    ENDRECORD];
  require_ae_noerr(getConnectionsEvent, cantHandleAppleEvent);
  NSAppleEventDescriptor *connections = [getConnectionsEvent sendWithImmediateReply];
  require_ae_noerr(connections, cantHandleAppleEvent);
  NSAppleEventDescriptor *connectionsList = [connections paramDescriptorForKeyword:keyDirectObject];
  require_ae_noerr(connectionsList, cantHandleAppleEvent);
  int count = [connectionsList numberOfItems];
  for (int i = 1; i <= count; i++) {
    NSAppleEventDescriptor *connection = [connectionsList descriptorAtIndex:i];
    require_ae_noerr(connection, cantHandleAppleEvent);
    NSAppleEventDescriptor *sendMessageEvent = [AEVT class:'ccoR'
                                                        id:'sRmX'
                                            targetBundleID:[self appBundleID],
                                                [KEY:'sRm1'], connection,  // target
                                                [KEY:'sRm2'], [BOOLEAN:false],  // priority
                                                [KEY:keyDirectObject], [STRING:[NSString stringWithFormat:@"away %@", newValue]],
                                                ENDRECORD];
    require_ae_noerr(sendMessageEvent, cantHandleAppleEvent);
    // Must set keySubjectAttr or Colloquy spits out an error at us.
    // Bad Colloquy.
    // See http://colloquy.info/project/ticket/1156
    // and http://www.cocoadev.com/index.pl?DirectParametersAsValues
    // for details.
    [sendMessageEvent setAttributeDescriptor:connection forKeyword:keySubjectAttr];
    NSAppleEventDescriptor* response = [sendMessageEvent sendWithImmediateReply];
    require_ae_noerr(response, cantHandleAppleEvent);
  }
  StatzUpdateValue value = kStatzUpdateNotChanged;
  if (count != 0) {
    [oldValue_ autorelease];
    oldValue_ = [newValue copy];
    value = kStatzUpdateSuccess;
  }
  return value;  
cantHandleAppleEvent:
  return kStatzUpdateError;
}

- (unsigned int)stateMenuMask { 
  return kStatzStateAvailable 
  | kStatzStateAway;
}
@end

